/***********************************************
 This file is part of redia-bapps-main-ios.
 
 Copyright (c) 2015 Redia A/S
 
 Redia-bapps-main-ios is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.
 
 Redia-bapps-main-ios is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
 
 You should have received a copy of the GNU General Public License
 along with redia-bapps-main-ios.  If not, see <http://www.gnu.org/licenses/>.
 
 *********************************************** */

//
//  BASlideInViewController.m
//  redia-bapps-ios
//
//  Created by Nikolaj Tørring on 10/22/13.
//  Copyright (c) 2013 redia. All rights reserved.
//

#import "BASlideInViewController.h"
#import <QuartzCore/QuartzCore.h>
#import "BACustomNavigationController.h"

@interface BASlideInViewController ()

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *slideInLeadingSpace;

@property (weak, nonatomic) IBOutlet UIView *rootView;
@property (weak, nonatomic) IBOutlet UIView *slideInView;

@property (nonatomic, strong) BACustomNavigationController* slideInNavigationController;
@property (nonatomic, strong) BACustomNavigationController* rootNavigationController;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *slideInWidth;

//We automatically set the delegate of the root view, if it conforms to the BASlideInViewControllerDelegate protocol.
//Discussion: Only the root view of the rootNavigationController can be set as the reciever, this could be a potential issue!
@property (nonatomic, weak) id<BASlideInViewControllerDelegate> delegate;


@end


@implementation BASlideInViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    //RD_SET_EDGES_FOR_EXTENDED_LAYOUT_IOS7
    
    [self.view.superview setFrame:self.view.bounds];
    
    self.slideInView.layer.shadowColor = [[UIColor blackColor] CGColor];
    self.slideInView.layer.shadowOpacity = 0.7;
    self.slideInView.layer.shadowRadius = 1.5;
    self.slideInView.layer.shadowOffset = CGSizeMake(-1.0f, 0.0f);
    self.slideInView.layer.shadowPath = [UIBezierPath bezierPathWithRect:self.slideInView.bounds].CGPath;
    
    _rootNavigationController = [[[NSBundle mainBundle] loadNibNamed:@"BACustomNavigationController" owner:self options:nil] objectAtIndex:0];
    [self.rootView addSubview:self.rootNavigationController.view];
    [self addChildViewController:self.rootNavigationController];
    [BAUtils setViewToFillParent:self.rootNavigationController.view];
    
    if (self.rootViewController != nil) {
        if ([self.rootViewController conformsToProtocol:@protocol(BASlideInViewControllerDelegate)]) {
            self.delegate = (id<BASlideInViewControllerDelegate>)self.rootViewController;
        }
        [self.rootNavigationController setViewControllers:@[self.rootViewController]];
    }
    
    _slideInNavigationController = [[[NSBundle mainBundle] loadNibNamed:@"BACustomNavigationController" owner:self options:nil] objectAtIndex:0];
    [self.slideInView addSubview:self.slideInNavigationController.view];
    [self addChildViewController:self.slideInNavigationController];
    [self.slideInView sendSubviewToBack:self.slideInNavigationController.view];
    self.slideInNavigationController.delegate = self;
    
    [BAUtils setViewToFillParent:self.slideInNavigationController.view];
    
    
    
}

-(void)viewWillAppear:(BOOL)animated{
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(BOOL)shouldAutorotate{
    return YES;
}

-(void)setRootViewController:(UIViewController *)rootViewController{
    if (!self.isViewLoaded) {
        _rootViewController = rootViewController;
    } else if (_rootViewController != rootViewController) {
        if (_rootViewController != nil) {
            [self.rootViewController viewWillDisappear:YES];
            [self.rootNavigationController setViewControllers:nil];
            [self.rootViewController removeFromParentViewController];
            [self.rootViewController.view removeFromSuperview];
            [self.rootViewController viewDidDisappear:YES];
            _rootViewController = nil;
        }
        if (rootViewController != nil) {
            if ([self.rootViewController conformsToProtocol:@protocol(BASlideInViewControllerDelegate)]) {
                self.delegate = (id<BASlideInViewControllerDelegate>)self.rootViewController;
            }
            [self.rootNavigationController setViewControllers:@[rootViewController]];

            _rootViewController = rootViewController;
        }
    }
}

-(void)slideInViewController:(UIViewController *)viewControllerToPresent animated:(BOOL)flag completion:(void (^)(void))completion{
    if (self.currentlyPresentedViewController != nil) {
        [self dismissSlideInViewControllerAnimated:flag force:NO completion:^{
            [self slideInViewController:viewControllerToPresent animated:flag completion:^{
                if (completion != nil) {
                    completion();
                }
            }];
        }];
        return;
    }
    _currentlyPresentedViewController = viewControllerToPresent;
    /*
    [self.slideInView addSubview:viewControllerToPresent.view];
    [self.slideInView sendSubviewToBack:viewControllerToPresent.view];
    [self addChildViewController:viewControllerToPresent];
    [self setViewToFillParent:viewControllerToPresent.view];
     */
    [self.slideInNavigationController setViewControllers:@[viewControllerToPresent]];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; \
    //if (mode == BASpecialNavigationBarDefault)
    [button setImage:[BAUtils instance].iPadGrayTopLeftClose forState:UIControlStateNormal];
    
    [button setFrame:CGRectMake(0, 0, 32, 32)];
    [button addTarget:self action:@selector(closeButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    
    if ([[BAUtils instance] iOSMajorVersion] > 6) {
        UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
        item.width = -6;
        [viewControllerToPresent.navigationItem setLeftBarButtonItems:@[item, [[UIBarButtonItem alloc] initWithCustomView:button]]];
    }
    else {
        UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
        item.width = 5;
        [viewControllerToPresent.navigationItem setLeftBarButtonItems:@[item, [[UIBarButtonItem alloc] initWithCustomView:button]]];
    }
    [self.slideInView layoutIfNeeded];
    
    
    if ([self.delegate respondsToSelector:@selector(slideInViewController:willOpenToWidth:withAnimationDuration:)]) {
        [self.delegate slideInViewController:self willOpenToWidth:self.slideInWidth.constant withAnimationDuration:(flag ? 0.3 : 0)];
    }
    
    if (!flag) {
        self.slideInLeadingSpace.constant = 0;
        [self.view layoutIfNeeded];
        if ([self.delegate respondsToSelector:@selector(slideInViewControllerDidOpen:)]) {
            [self.delegate slideInViewControllerDidOpen:self];
        }
        if (completion != nil) {
            completion();
        }
    } else{
        [UIView animateWithDuration:0.3 delay:0 options:(UIViewAnimationOptionAllowAnimatedContent | UIViewAnimationOptionOverrideInheritedOptions) animations:^{
            self.slideInLeadingSpace.constant = 0;
            [self.view layoutIfNeeded];
        } completion:^(BOOL finished) {
            if ([self.delegate respondsToSelector:@selector(slideInViewControllerDidOpen:)]) {
                [self.delegate slideInViewControllerDidOpen:self];
            }
            if (completion != nil) {
                completion();
            }
        }];
    }
    
    
}

-(void)dismissSlideInViewControllerAnimated:(BOOL)dismissAnimated force:(BOOL)force completion:(void (^)(void))completion{
    if (self.currentlyPresentedViewController == nil) {
        if (completion != nil) {
            completion();
        }
        return;
    }
#if defined(BA_LIBRARIAN_BUILD) || defined(BA_IMF_BUILD)
    UIViewController* vc = [self.slideInNavigationController.viewControllers firstObject];
    if ([vc respondsToSelector:@selector(shouldDismissFromSlideInController:)] && !force) {
        BASlideInViewController* slidInView = self;
        NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:
                                    [[vc class] instanceMethodSignatureForSelector:@selector(shouldDismissFromSlideInController:)]];
        [invocation setSelector:@selector(shouldDismissFromSlideInController:)];
        [invocation setTarget:vc];
        [invocation setArgument:&slidInView atIndex:2]; //Not realy needed.
        [invocation invoke];
        BOOL returnValue;
        [invocation getReturnValue:&returnValue];
        
        if (returnValue == NO) {
            return;
        }
//        [vc performSelector:@selector(shouldDismissFromSlideInController:) withObject:self ];
    }
#endif

    if ([self.delegate respondsToSelector:@selector(slideInViewController:willCloseWithAnimationDuration:)]) {
        [self.delegate slideInViewController:self willCloseWithAnimationDuration:(dismissAnimated ? 0.3 : 0)];
    }
    
    [UIView animateWithDuration:(dismissAnimated ? 0.3 : 0) delay:0 options:(UIViewAnimationOptionAllowAnimatedContent | UIViewAnimationOptionOverrideInheritedOptions | UIViewAnimationOptionBeginFromCurrentState) animations:^{
        self.slideInLeadingSpace.constant = 1030;
        [self.view layoutIfNeeded];
    } completion:^(BOOL finished) {
        [self.slideInNavigationController setViewControllers:nil];
        if ([self.delegate respondsToSelector:@selector(slideInViewControllerDidClose:)]) {
            [self.delegate slideInViewControllerDidClose:self];
        }
        /*
        [self.slideInViewController viewWillDisappear:YES];
        [self.slideInViewController removeFromParentViewController];
        [self.slideInViewController.view removeFromSuperview];
        [self.slideInViewController viewDidDisappear:YES];
         */
        _currentlyPresentedViewController = nil;
        if (completion != nil) {
            completion();
        }
    }];
}

- (IBAction)closeButtonClicked:(id)sender {
    [self dismissSlideInViewControllerAnimated:YES force:NO completion:nil];
}

+(BASlideInViewController*)findSlideInViewController:(UIViewController*)viewController{
    id vc = viewController;
    do {
        vc = [(UIViewController*)vc parentViewController];
        if ([vc isKindOfClass:[BASlideInViewController class]]) {
            break;
        }
    } while (vc != nil);
    return vc;
}

@end
